<?php

namespace addons\qingdongams\model;

use think\Exception;
use think\Model;
use traits\model\SoftDelete;

/**
 *回款表
 */
class Receivables Extends Model {
	use SoftDelete;
    // 表名,不含前缀
    protected $name = 'qingdongams_receivables';
	// 开启自动写入时间戳字段
	protected $autoWriteTimestamp = 'int';
	// 定义时间戳字段名
	protected $createTime = 'createtime';
	protected $updateTime = 'updatetime';
	protected $deleteTime = 'deletetime';

	//创建回款
	public static function createReceivables($params) {
		//自定义字段
		$other = [];
		foreach ($params as $name => $val) {
			if (strstr($name,'other_') !== false) {
                if(is_array($val)){
                    $other[$name] = implode(',',$val);
                }else{
                    $other[$name] = $val;
                }
				unset($params[$name]);
			}else{
                if(empty($params[$name])){
                    $params[$name]=NULL;
                }
            }
		}
		$staff                     = Staff::info();
		$params['create_staff_id'] = $staff->id;
		$params['owner_staff_id']  = isset($params['owner_staff_id']) ? $params['owner_staff_id'] :$staff->id;
		$params['check_status']    = 1;
        $flow = Flow::getsteplist(Flow::RECEIVABLES_STATUS);
        $params['flow_id'] = $flow['flow_id'];
        $params['order_id'] = $flow['order_id'];
        if ($flow['status'] == 0) {//发起人自选
            if (empty($params['flow_staff_ids'])) {
                throw new Exception('审批人必须选择');
            }
            $params['flow_staff_ids'] = trim($params['flow_staff_ids']);
        } else {
            $params['flow_staff_ids'] = trim($flow['flow_staff_ids']);
        }

		$Model                     = new self;
        $result = $Model->allowField(true)->save($params);
		if (false === $result) {
			// 验证失败 输出错误信息
			throw new Exception($Model->getError());
		}
		$lastId=$Model->getLastInsID();
		$otherModel = new ReceivablesOther();
		if ($otherModel->where(['id' => $lastId])->update([ 'otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)]) === false) {
			// 验证失败 输出错误信息
			throw new Exception($otherModel->getError());
		}

		if (isset($params['plan_id']) && $params['plan_id']) {//修改回款计划为已完成
			ReceivablesPlan::where(['id' => $params['plan_id']])->update(['status' => 1]);
		}

        if ($flow['status'] == 1) {//固定审批
            //发送审批通知
            Flow::sendStepRecord($flow,Flow::RECEIVABLES_STATUS, $lastId);
        } else {//发起人自选 依次审批
            $staff_id   = explode(',', $params['flow_staff_ids'])[0];
            if ($staff_id) {
                ExamineRecord::addExaminse(ExamineRecord::RECEIVABLES_TYPE, $lastId, $staff_id);
            }
        }

		Record::quickCreateRecord(Record::CUSTOMER_TYPE, $params['customer_id'], '创建回款:' . $params['number']);
		return true;
	}
	/**
	 *修改回款信息
	 */
	public static function updateReceivables($params) {
		//自定义字段
		$other = [];
		foreach ($params as $name => $val) {
			if (strstr($name,'other_') !== false) {
                if(is_array($val)){
                    $other[$name] = implode(',',$val);
                }else{
                    $other[$name] = $val;
                }
				unset($params[$name]);
			}else{
                if(empty($params[$name])){
                    $params[$name]=NULL;
                }
            }
		}
        $flow = Flow::getsteplist(Flow::RECEIVABLES_STATUS);
        $params['flow_id'] = $flow['flow_id'];
        $params['order_id'] = $flow['order_id'];

        if ($flow['status'] == 0) {//发起人自选
            if (empty($params['flow_staff_ids'])) {
                throw new Exception('审批人必须选择');
            }
            $params['flow_staff_ids'] = trim($params['flow_staff_ids']);
        } else {
            $params['flow_staff_ids'] = trim($flow['flow_staff_ids']);
        }

		$Model = new self;
		$params['check_status']    = 1;
		// 调用当前模型对应的User验证器类进行数据验证
		$result = $Model->save($params, ['id' => $params['id']]);
		if (false === $result) {
			// 验证失败 输出错误信息
			throw new Exception($Model->getError());
		}
		$otherModel = new ReceivablesOther();
		if ($otherModel->save(['otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)],['id' => $params['id']]) === false) {
			// 验证失败 输出错误信息
			throw new Exception($otherModel->getError());
		}

        if ($flow['status'] == 1) {//固定审批
            //发送审批通知
            Flow::sendStepRecord($flow,Flow::RECEIVABLES_STATUS, $params['id']);
        } else {//发起人自选 依次审批
            $staff_id   = explode(',', $params['flow_staff_ids'])[0];
            if ($staff_id) {
                ExamineRecord::addExaminse(ExamineRecord::RECEIVABLES_TYPE, $params['id'], $staff_id);
            }
        }
		return true;
	}

	//客户
	public function customer() {
		return $this->hasOne(Customer::class, 'id', 'customer_id')->field('id,name,subname,user_id, jigou_id');
	}


	//订单
	public function contract() {
		return $this->hasOne(Contract::class, 'id', 'contract_id')->field('id,name,num,money');
	}
    //获取回款相关信息
    public function receivablesOther() {
        return $this->belongsTo(ReceivablesOther::class,'id','id');
    }

    //导入回款
    public static function importReceivables($data) {
        $addReceivables = [];
        $addOther     = [];
        foreach ($data as $params) {
            //自定义字段
            $other = [];
            foreach ($params as $name => $val) {
                if (strstr($name, 'other_') !== false) {
                    if(is_array($val)){
                        $other[$name] = implode(',',$val);
                    }else{
                        $other[$name] = $val;
                    }
                    unset($params[$name]);
                }else{
                    if(empty($params[$name])){
                        $params[$name]=NULL;
                    }
                }
            }
            $params['createtime'] = time();
            $params['updatetime'] = time();
            $params['check_status']   = 2;
            $other['id']           = $params['id'];
            $addOther[]            = ['id' => $params['id'], 'otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)];
            $addReceivables[]        = $params;
        }

        $model = new self;
        // 调用当前模型对应的User验证器类进行数据验证
        $result = $model->allowField(true)->insertAll($addReceivables);

        $otherModel = new ReceivablesOther();
        $otherModel->allowField(true)->insertAll($addOther);

        return true;
    }

	//
	public function ownerStaff() {
		return $this->hasOne(Staff::class, 'id', 'owner_staff_id')->field('id,name,img')->removeOption('soft_delete');
	}

	//
	public function createStaff() {
		return $this->hasOne(Staff::class, 'id', 'create_staff_id')->field('id,name,img');
	}


	//
	public function staff() {
		return $this->hasOne(Staff::class, 'id', 'owner_staff_id')->field('id,name,img,department_id,post');
	}


	//
	public function getCreatetimeAttr($value) {
		return date('Y-m-d H:i', $value);
	}
	//
	public function getUpdatetimeAttr($value) {
		return date('Y-m-d H:i', $value);
	}

	//回款期数
	public function plan() {
		return $this->hasOne(ReceivablesPlan::class, 'id', 'plan_id')->field('id,num,money');
	}
    public static function getNum()
    {
        return 'R' . date('Ymd') . rand(10000,99999);
    }
}
